package web.user;

import cn.itcast.commons.CommonUtils;
import domain.user.User;
import service.user.UserException;
import service.user.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 文件描述
 * 登录Servlet  userWeb层
 *
 * @author 冯根源
 * @date 2020/3/18 18:32
 */
@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");//请求访问编码
        response.setContentType("text/html;charset=utf-8");//响应编码

        //依赖UserService
        UserService userService = new UserService();

        //封装表单数据
        User userForm = CommonUtils.toBean(request.getParameterMap(), User.class);
        try {
            User user = userService.login(userForm);
            request.getSession().setAttribute("sessionUser",user);
            response.sendRedirect(request.getContextPath()+"/user/welcome.jsp");
        } catch (UserException e) {
            request.setAttribute("error", e.getMessage());
            request.setAttribute("user", userForm);
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }


}
